package com.b511.swpu.cementbackend.service.impl;

import com.b511.swpu.cementbackend.entity.CementingConstructData;
import com.b511.swpu.cementbackend.exception.CementException;
import com.b511.swpu.cementbackend.repository.CementingConstructDataRepository;
import com.b511.swpu.cementbackend.service.CementingConstructDataService;
import com.b511.swpu.cementbackend.util.enumeration.Code;
import com.b511.swpu.cementbackend.util.CopyUtil;
import com.b511.swpu.cementbackend.util.R;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
public class CementingConstructDataServiceImpl implements CementingConstructDataService {

    private final CementingConstructDataRepository cementingConstructDataRepository;

    public CementingConstructDataServiceImpl(CementingConstructDataRepository cementingConstructDataRepository) {
        this.cementingConstructDataRepository = cementingConstructDataRepository;
    }

    @Override
    public R getCementingConstructData(PageRequest pageRequest) {
        return R.ok().putData(cementingConstructDataRepository.findAll(pageRequest));
    }

    @Override
    @Transactional
    public R updateCementingConstructData(Long id, CementingConstructData updateCementingConstructData) {
        Optional<CementingConstructData> optionalCementingConstructData = cementingConstructDataRepository.findById(id);
        if (!optionalCementingConstructData.isPresent()) {
            throw new CementException(Code.SELECT_FAIL);
        }
        CementingConstructData cementingConstructData = optionalCementingConstructData.get();
        CopyUtil.copyProperties(updateCementingConstructData, cementingConstructData);
        cementingConstructDataRepository.save(cementingConstructData);
        return R.ok();
    }
}
